package com.sso.action.sys;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sso.action.BaseAction;
import com.sso.common.ConstantDate;
import com.sso.common.enums.FlagStatus;
import com.sso.common.enums.SysUserEnum;
import com.sso.entity.*;
import com.sso.entity.vo.SysUserVo;
import com.sso.exception.SelectException;
import com.sso.manager.*;
import com.tools.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class SysUserAction extends BaseAction {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysUserManager manager;
    @Autowired
    private SysUserRoleManager userRoleManager;
    @Autowired
    private SysUserMenuManager userMenuManager;
    @Autowired
    private SysRoleManager roleManager;
    @Autowired
    private SysMenuManager menuManager;

    @RequestMapping("save")
    public void register(SysUser user, HttpServletRequest request, HttpServletResponse response) {
        String flag = FlagStatus.ERROR.value;
        if (user == null) {
            this.outputJson(flag, "注册用户信息不完整，请重新输入!", response);
            return;
        }
        JSONObject usernameJson = this.ckeckUsername(user.getUsername());
        if (FlagStatus.ERROR.value.equals(usernameJson.get("status"))) {
            this.outputJson(usernameJson, response);
            return;
        }
        JSONObject passwordJson = this.ckeckPassword(user.getPassword());
        if (FlagStatus.ERROR.value.equals(passwordJson.get("status"))) {
            this.outputJson(passwordJson, response);
            return;
        }
        if (StrUtils.isNull(user.getRealname()) || StrUtils.isEmpty(user.getRealname())) {
            this.outputJson(flag, "请输入真实姓名", response);
            return;
        }
        try {
            flag = manager.save(user);
            this.outputJson(flag, "注册成功", response);
        } catch (Exception e) {
            e.printStackTrace();
            this.outputJson(flag, "注册失败,请联系管理人员", response);
        }
    }

    /**
     * 校验用户
     *
     * @param param
     * @param name
     * @param request
     * @param response
     */
    @RequestMapping("ckeckUser")
    public void checkUser(String param, String name, HttpServletRequest request, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        if ("username".equals(name)) {
            json = this.ckeckUsername(param);
            this.outputJson(json, response);
            return;
        } else if ("password".equals(name)) {
            json = this.ckeckPassword(param);
            this.outputJson(json, response);
            return;
        }
    }

    /**
     * 查询用户名是否正确及未被占用
     *
     * @param username
     * @return
     */
    private JSONObject ckeckUsername(String username) {
        //用户名正则表达式
        String usernameMatches = PropertiesUtils.getValueByProperty("username", "/config/mathces.properties");
        if (StrUtils.isNull(username) || StrUtils.isEmpty(username)) {
            return this.getErrorJson("请输入用户名");
        }
        if (!username.matches(usernameMatches)) {
            return this.getErrorJson("用户名格式不正确");
        }
        SysUser user = manager.selectByUsername(username);
        if (StrUtils.isNotEmpty(user.getId())) {
            return this.getErrorJson("此用户名已被注册请重新输入");
        }
        return this.getSuccessJson("用户名未被注册");
    }

    /**
     * 查询密码是否正确
     *
     * @return
     */
    private JSONObject ckeckPassword(String password) {
        //用户名正则表达式
        String pwdMatches = PropertiesUtils.getValueByProperty("password", "/config/mathces.properties");
        if (StrUtils.isNull(password) || StrUtils.isEmpty(password)) {
            return this.getErrorJson("请输入密码");
        }
        if (!password.matches(pwdMatches)) {
            return this.getErrorJson("密码格式不正确，请重新输入");
        }
        return this.getSuccessJson("");
    }

    @RequestMapping("/gotoUserManagerView")
    public ModelAndView gotoUserManagerView(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView view = new ModelAndView("/manager/sysUserManagerView");
        Map<String, Object> filterMap = RequestUtils.getParametersToMap(request, "");
        try {
            Page<SysUserVo> page = manager.selectByPageToVo(filterMap);
            view.addObject("page", page);
        } catch (SelectException e) {
            e.printStackTrace();
        }
        return view;
    }

    /**
     * 查询用户详细信息
     * @param request
     * @param response
     * @Param username 用户名
     * @return
     */
    @RequestMapping("/userInfo")
    public void userInfo(HttpServletRequest request,HttpServletResponse response) {
        String id = RequestUtils.getParameters(request,"userId");
        SysUser user = manager.selectById(id);
        SysUserVo vo = BeanUtils.copyBean(user,SysUserVo.class);
        String notInAttr="password";
        Object json = JSONObject.parse(JSONUtils.toJsonNotInAttrbuite(vo,notInAttr));
        this.outputJson(FlagStatus.SUCCESS.value,json,response);
    }

    @RequestMapping("/selectRoleByUserToJSON")
    public void selectRoleByUserToJSON(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> param = RequestUtils.getParametersToMap(request, "");
        String userId = (String) param.get("userId");
        JSONObject json = new JSONObject();
        List<SysUserRole> list = userRoleManager.selectByUserId(userId);
        String jsonStr = JSONArray.toJSONString(list);
        json.put("status", FlagStatus.SUCCESS.value);
        json.put("info", jsonStr);
        this.outputJson(json, response);
    }

    /**
     * 保存用户权限
     *
     * @param authType 权限类型:1、角色类型 2、菜单类型
     * @param request
     * @param response
     */
    @RequestMapping("saveUserAuth")
    public void saveUserAuth(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> param = RequestUtils.getParametersToMap(request, "");
        String[] checkIdArray = RequestUtils.getParameterValues(request,"checkId");
        String authType = (String) param.get("authType");
        String userid = (String) param.get("userId");
        SysUser user = manager.selectById(userid);
        String status = FlagStatus.ERROR.value;
        if (StrUtils.isEmpty(user.getId())) {
            this.outputJson(status, "要授权的用户不存在", response);
            return;
        }
        try {
            //查询条件，由于两张表主键都叫ID并且主键数组查询都叫idArray同时又共用一个参数所以放到外面
            param.put("idArray", checkIdArray);
            //角色类型
            if ("1".equals(authType)) {
                //如果没有角色走else方法
                List<SysRole> list = new ArrayList<SysRole>();
                if(checkIdArray!=null) {
                    list = roleManager.selectByProperty(param);
                }
                manager.saveUserRole(list, user);
                //菜单类型
            } else if ("2".equals(authType)) {
                List<SysMenu> menuList = new ArrayList<SysMenu>();
                if(checkIdArray!=null) {
                    menuList = menuManager.selectByProperty(param);
                }
                manager.saveUserMenu(menuList, user);
                //错误类型
            } else {
                this.outputJson(status, "权限类型错误", response);
                return;
            }
            this.outputJson(FlagStatus.SUCCESS.value, "授权成功", response);
        } catch (Exception e) {
            e.printStackTrace();
            this.outputJson(FlagStatus.ERROR.value, "操作失败，请联系管理人员", response);
        }
    }

    /**
     * 查询用户角色权限信息
     *
     * @param userId    要查询的用户角色ID
     * @param request
     * @param responser
     */
    @RequestMapping("selectUserRoleAuth")
    public void selectUserRoleAuthToJSON(HttpServletRequest request, HttpServletResponse responser) {
        this.selectUserAuth("1",request,responser);
    }

    /**
     * 查询用户菜单权限信息
     * @param userId 要查询的用户角色ID
     * @param request
     * @param response
     */
    @RequestMapping("selectUserMenuAuth")
    public void selectUserMenuAuthToJSON(HttpServletRequest request,HttpServletResponse response){
        this.selectUserAuth("2",request,response);
    }

    /**
     * 激活用户
     * @param userId 用户ID
     * @param request
     * @param response
     */
    @RequestMapping("userActivate")
    public void userActivate(HttpServletRequest request,HttpServletResponse response){
        String id = RequestUtils.getParameters(request,"userId");
        String status = FlagStatus.ERROR.value;
        SysUser user = manager.selectById(id);
        if(StrUtils.isEmpty(user.getId())){
            this.outputJson(status,"请选择要激活的用户",response);
            return;
        }
        if(SysUserEnum.status.ACTIVATE.equals(user.getStatus())){
            this.outputJson(status,"该用户已激活，不需要再次操作",response);
            return;
        }
        user.setStatus(SysUserEnum.status.ACTIVATE.key);
        try {
            manager.save(user);
            this.outputJson(FlagStatus.SUCCESS.value,"激活成功",response);
        } catch (Exception e) {
            e.printStackTrace();
            this.outputJson(status,"激活失败，请联系管理人员",response);
        }

    }

    /**
     * 取消激活
     * @param userId 用户ID
     * @param request
     * @param response
     */
    @RequestMapping("userFrozen")
    public void userFrozen(HttpServletRequest request,HttpServletResponse response){
        String id = RequestUtils.getParameters(request,"userId");
        String status = FlagStatus.ERROR.value;
        SysUser user = manager.selectById(id);
        if(StrUtils.isEmpty(user.getId())){
            this.outputJson(status,"请选择要取消激活的用户",response);
            return;
        }
        if(SysUserEnum.status.ACTIVATE.equals(user.getStatus())){
            this.outputJson(status,"该用户已取消激活，请勿重复操作",response);
            return;
        }
        if(SysUserEnum.status.DEL.equals(user.getStatus())){
            this.outputJson(status,"该用户已删除不需要取消激活",response);
            return;
        }
        user.setStatus(SysUserEnum.status.FREEZE.key);
        try {
            manager.save(user);
            this.outputJson(FlagStatus.SUCCESS.value,"取消激活成功",response);
        } catch (Exception e) {
            e.printStackTrace();
            this.outputJson(status,"取消激活失败，请联系管理人员",response);
        }

    }

    /**
     * 删除用户
     * @param userId 用户ID
     * @param request
     * @param response
     */
    @RequestMapping("userDelete")
    public void userDelete(HttpServletRequest request,HttpServletResponse response){
        String id = RequestUtils.getParameters(request,"userId");
        String status = FlagStatus.ERROR.value;
        SysUser user = manager.selectById(id);
        if(StrUtils.isEmpty(user.getId())){
            this.outputJson(status,"请选择要删除的用户",response);
            return;
        }
        if(SysUserEnum.status.DEL.equals(user.getStatus())){
            this.outputJson(status,"该用户已被删除，请勿重复操作",response);
            return;
        }
        user.setStatus(SysUserEnum.status.DEL.key);
        try {
            manager.save(user);
            this.outputJson(FlagStatus.SUCCESS.value,"删除成功",response);
        } catch (Exception e) {
            e.printStackTrace();
            this.outputJson(status,"取消激活失败，请联系管理人员",response);
        }
    }

    /**
     * 刷新所有用户权限
     */
    @RequestMapping("refreshAllUserAuth")
    public void refreshAllUserAuth(HttpServletResponse response){
        this.manager.clearAllUserAuth();
        this.outputJson(FlagStatus.SUCCESS.value,"刷新成功", response);
    }

    /**
     * 查询用户权限信息，返回一个标准的json
     * 其中info信息为一个JSONArray
     * @param authType
     * @param request
     * @param response
     */
    private void selectUserAuth(String authType,HttpServletRequest request,HttpServletResponse response){
        String userid = RequestUtils.getParameters(request, "userId");
        SysUser user = manager.selectById(userid);
        if (StrUtils.isEmpty(user.getId())) {
            this.outputJsonFalse("用户不存在", response);
            return;
        }
        if("1".equals(authType)){
            List<SysUserRole> userRoleList = userRoleManager.selectByUserId(user.getId());
            this.outputJson(FlagStatus.SUCCESS.value,userRoleList,response);
        }else{
            List<SysUserMenu> userMenuList = userMenuManager.selectByUserId(user.getId());
            this.outputJson(FlagStatus.SUCCESS.value,userMenuList,response);
        }
    }
}
